<template>
	<view>
		<u-navbar :title="groupname" placeholder autoBack titleStyle="color:#fff" leftIconColor="#ffffff" bgColor="#c1282e">
			<view class="flexright xiaobai" slot="right" @click="jumpdetail('/pages/tab5/groupInfo?id=',group_id)">
				<u-icon name="more-dot-fill" color="#ffffff" size="16"></u-icon>
			</view>
		</u-navbar>
		<view class="cu-chat" style="padding-bottom: 180rpx;" v-if="updatechatflag">
			<view class="" id="scroll-view-content">
				<view class="" :id="'maodian'+item.id" v-for="item in list.data" :key="item.id">
					<view class="flexcenter" v-if="item.is_timeshow">
						<view class="cu-info  round">{{item.createtime_text}}</view>
					</view>
					<view class="flexcenter" v-if="item.msg_status==2">
						<view class="cu-info  round">{{item.user_id==user_id?'你':item.username}}撤回了一条消息</view>
					</view>
					<view class="cu-item" :class="item.user_id==user_id?'self':''"  v-if="item.msg_status==1">
						<!-- 好友的头像 -->
						<view class="cu-avatar radius" v-show="item.user_id!=user_id"
							:style="{backgroundImage:'url('+item.avatar+')'}"></view>
						<!-- //1=文字,2=图片,3=视频 -->
						<view class="main" v-if="item.data_type==1">
							<view class="content shadow" style="display: flex;"
								:class="item.user_id==user_id?'lanbgc':'huigbc'"  @longpress="backMsg(item)">
								<text>{{item.content}}</text>
							</view>
						</view>
						<!-- 图片 -->
						<view class="main" v-if="item.data_type==2">
							<view class="" @click="lbtpriview(0,[item.content_text])"  @longpress="backMsg(item)">
								<image style="width: 300rpx;border-radius: 10rpx;" :src="item.content_text"
									mode="widthFix"></image>
							</view>
						</view>
						<view class="main" v-if="item.data_type==4">
							<view class="flexleft" @click="downloaditem(item.content_text)"  @longpress="backMsg(item)">
								<image style="width: 100rpx;margin-right: 15rpx;" src="@/static/chat5.png"
									mode="widthFix"></image>
								<text>发来一个文件</text>
							</view>
						</view>
						<!-- 视频 -->
						<!-- <view class="main" v-if="item.data_type==3">
							<view class="">
								<video style="width: 400rpx;height: 300rpx;" :id="'videoId'+item.id"
									:src="item.message_text" @play="play(item.id)"
									@fullscreenchange="fullscreenchange($event,item.id)" v-show="isVideoShow"></video>
								<view class="videoBox" @click="playBox(item.id)"
									:style="{backgroundImage:'url('+item.message_text+'?x-oss-process=video/snapshot,t_10000,m_fast'+')'}"
									v-show="!isVideoShow"></view>
							</view>
						</view> -->
						<!-- 我的头像 -->
						<view class="cu-avatar radius" :style="{backgroundImage:'url('+item.avatar+')'}"
							v-show="item.user_id==user_id"></view>
					</view>
				</view>
			</view>
		</view>
		<view class="foot">

			<view class="cu-bar input mainpadding" v-if="groupInfo.jy_status==1 || groupInfo.user_id==user_id">
				<!-- 输入框 -->
				<textarea class="solid-bottom xiaohei" style="height: 60rpx;" cursor-spacing="200" placeholder="输入新消息"
					confirm-type="send" @confirm="send()" maxlength="300" v-model="content"
					@focus="callPhoneShow=false"></textarea>
				<view class="" @click="callPhoneShow=!callPhoneShow">
					<u-icon name="plus-circle" color="#333" size="28"></u-icon>
				</view>
				<view class="lanbgc flexcenter" style="width: 100rpx;height: 50rpx;" @click="send()">发送</view>
			</view>
			<view class="cu-bar input mainpadding" v-if="groupInfo.jy_status==2 && groupInfo.user_id!=user_id">
				<!-- 如果禁言情况下非群主可以发送常用语 -->
				<textarea class="solid-bottom xiaohei" style="height: 60rpx;" cursor-spacing="200" disabled=""
					placeholder="该群禁言中" confirm-type="send" @confirm="send()" maxlength="300" v-model="content"
					@focus="callPhoneShow=false"></textarea>
				<view class="" @click="callPhoneShow=!callPhoneShow">
					<u-icon name="plus-circle" color="#333" size="28"></u-icon>
				</view>
			</view>
			<template v-if="callPhoneShow">
				<view class="emote service_box">
					<view class="flexleft flex-wrap ">
						<view class="item_service_box flexcolumn margin_top5" v-if="groupInfo.jy_status==1 || groupInfo.user_id==user_id"
							@click="uploadImg(0)">
							<image src="@/static/chat1.png" class="item_emote_img" mode=""></image>
							<view class="smalltext xiaohei">相机</view>
						</view>
						<view class="item_service_box flexcolumn margin_top5" v-if="groupInfo.jy_status==1 || groupInfo.user_id==user_id"
							@click="uploadImg(1)">
							<image src="@/static/chat2.png" class="item_emote_img" mode=""></image>
							<view class="smalltext xiaohei">相册</view>
						</view>
						<view class="item_service_box flexcolumn margin_top5" v-if="groupInfo.jy_status==1 || groupInfo.user_id==user_id" @click="uploadImg(2)">
							<image src="@/static/chat3.png" class="item_emote_img" mode=""></image>
							<view class="smalltext xiaohei">文件</view>
						</view>
						<view class="item_service_box flexcolumn margin_top5"
							@click="callPhoneShow=false;cyyshow = true">
							<image src="@/static/chat4.png" class="item_emote_img" mode=""></image>
							<view class="smalltext xiaohei">常用语</view>
						</view>
					</view>
				</view>
			</template>
		</view>
		<u-modal :show="cyyshow" title="常用语" showCancelButton cancelText="编辑"
			@cancel="jumpdetail('/pages/tab5/changyongy?id=',group_id)" confirmColor="#c1282e" confirmText="关闭"
			@confirm="cyyshow = false">
			<view class="slot-content" style="width: 100%;">
				<scroll-view scroll-y="true" style="max-height: 500rpx;width: 100%;">
					<view>
						<view class="flexbetween margin_top pdl" v-for="item in cyylist" :key="item.id"
							style="width: 100%;">
							<view class="xiaohei main_size">{{item.content}}</view>
							<view class="lanbgc flexcenter" style="width: 100rpx;height: 50rpx;"
								@click="send(item.content)">发送</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</u-modal>
		<xe-upload ref="XeUpload" :options="uploadOptions" @callback="handleUploadCallback"></xe-upload>
	</view>
</template>

<script>
	const httpRequest = require("@/common/httpRequest.js")
	import WebSocket from '@/static/websocket.js' //websocket封装
	export default {
		data() {
			return {
				content: "",
				scrollTop: "",
				user_id: "", //本人id
				emoteShow: false, //表情是否展示
				isSendShow: false, //加号、发送按钮是否展示
				liwushow: false,
				page: 1,
				list: {
					data: []
				},
				isVideoShow: false, //是否显示视频
				WebSocket,
				group_id: "", //群聊id
				groupname: "", //群聊名称
				currenti: 1,
				callPhoneShow: false,
				isload: false,
				groupInfo: {},
				updatechatflag: true,
				cyyshow: false,
				cyylist: [],
				uploadOptions:{}
			}
		},
		watch: {
			content(newVal) {
				newVal ? this.isSendShow = true : this.isSendShow = false
			}
		},
		onLoad(options) {
			let data = JSON.parse(decodeURIComponent(options.msg));
			console.log(data, "接受参数");
			this.user_id = uni.getStorageSync("user_id")
			this.group_id = data.group_id
			this.groupname = data.groupname
			uni.$on("updatechatFnte", data => {
				console.log("触發方法了哈哈哈");
				this.updatechat()
			})
			uni.$on("chexiaogroupmsg", data => {
				console.log("监听到群聊对方撤回消息了", data);
				this.list.data.forEach(current => {
					if (current.id == data) {
						current.msg_status = 2
					}
				})
			})
			this.init()
		},
		onShow() {
			this.getGroupInfo()
			this.getcyy()
		},
		onUnload() {
			uni.$off('updatechatFnte')
			uni.$off('chexiaogroupmsg')
		},
		onPullDownRefresh() { //下拉刷新
			let _this = this;
			let list = _this.list;
			let page = _this.page;
			if (list.last_page <= page) {
				uni.stopPullDownRefresh()
				return false;
			}
			page++;
			_this.page = page;
			_this.init(true, page);
		},
		methods: {
			handleUploadCallback(e) {
				console.log("選擇的文件》》》",e);
				this.FILEuploadImageService(e.data[0].tempFilePath)
			},
			getcyy() {
				httpRequest.request('/webim/Groups/cyyIndex', 'GET', {
					webim_groups_id: this.group_id,
				}).then(res => {
					this.cyylist = res.data
				})
			},
			getGroupInfo() {
				httpRequest.request('/webim/Groups/groupProfile', 'GET', {
					client_id: uni.getStorageSync("client_id"),
					groupid: this.group_id,
				}).then(res => {
					this.groupInfo = res.data
				})
			},
			uploadImg(val) { //上传图片
				let _this = this
				if (val == 0) {
					httpRequest.chooseImage(1, ['camera']).then(res => {
						for (var i = 0; i < res.length; i++) {
							_this.IMGuploadImageService(res[i])
						}
					}).catch(err => {});
				}
				// 选择相册走1
				if (val == 1) {
					httpRequest.chooseImage(1, ['album']).then(res => {
						for (var i = 0; i < res.length; i++) {
							_this.IMGuploadImageService(res[i])
						}
					}).catch(err => {});
				}
				// 选择文件走2
				if (val == 2) {
					// #ifdef APP-PLUS
						this.$refs.XeUpload.upload('file', {});
					// #endif
					// #ifdef H5
					uni.chooseFile({
						count: 1,
						extension: ['doc', 'word', 'docx', 'pdf'],
						success(res) {
							console.log(res, "999");
							for (let i = 0; i < res.tempFiles.length; i++) {
								_this.FILEuploadImageService(res.tempFiles[i].path)
							}
						}
					})
					// #endif
				}
			},
			downloaditem(url) {
				uni.downloadFile({
					url, //下载地址接口返回
					success: (data) => {
						if (data.statusCode === 200) {
							//隐藏加载框
							uni.hideLoading();
							//文件保存到本地
							uni.saveFile({
								tempFilePath: data.tempFilePath, //临时路径
								success: function(res) {
									uni.showToast({
										icon: 'success',
										mask: true,
										// title: '文件已保存：' + res.savedFilePath, //保存路径
										title: '下载成功',
										duration: 2000,
									});
									//自动打开文档查看
									setTimeout(() => {
										var filePath = res.savedFilePath;
										uni.openDocument({ //新开页面打开文档，支持格式：doc, xls, ppt, pdf, docx, xlsx, pptx。
											filePath: filePath,
											showMenu: true,
											success: function(res) {}
										});
									}, 500)
								}
							});
						}
					},
					fail: (err) => {
						console.log(err);
						uni.showToast({
							icon: 'none',
							mask: true,
							title: '文件下载失败',
						});
					},
				});
			},
			FILEuploadImageService(url) { //图片转载
				let _this = this;
				let groupinfo = this.groupInfo
				httpRequest.uploadFile('/api/common/upload', url).then(res => {
					let data = {
						mine: {
							id: uni.getStorageSync("user_id"),
							content: res.url,
							data_type: 4, //1=文字,2=图片,3=视频
						},
						to: {
							groups_id: this.group_id,
							groupname: groupinfo.name,
							avatar: groupinfo.icon,
							sign: groupinfo.intro,
							id: groupinfo.id,
							groups: {
								id: groupinfo.id,
								name: groupinfo.name,
								user_id: groupinfo.user_id,
								icon: groupinfo.icon,
								intro: groupinfo.intro,
								status: groupinfo.status,
								createtime: groupinfo.createtime,
								updatetime: groupinfo.updatetime,
								deletetime: ""
							},
							name: groupinfo.name,
							type: "group"
						},
						client_id: uni.getStorageSync("client_id")
					}
					this.sendother(data)
				}).catch(err => {});
			},
			IMGuploadImageService(url) { //图片转载
				let _this = this;
				let groupinfo = this.groupInfo
				httpRequest.uploadFile('/api/common/upload', url).then(res => {
					let data = {
						mine: {
							id: uni.getStorageSync("user_id"),
							content: res.url,
							data_type: 2, //1=文字,2=图片,3=视频
						},
						to: {
							groups_id: this.group_id,
							groupname: groupinfo.name,
							avatar: groupinfo.icon,
							sign: groupinfo.intro,
							id: groupinfo.id,
							groups: {
								id: groupinfo.id,
								name: groupinfo.name,
								user_id: groupinfo.user_id,
								icon: groupinfo.icon,
								intro: groupinfo.intro,
								status: groupinfo.status,
								createtime: groupinfo.createtime,
								updatetime: groupinfo.updatetime,
								deletetime: ""
							},
							name: groupinfo.name,
							type: "group"
						},
						client_id: uni.getStorageSync("client_id")
					}
					this.sendother(data)
				}).catch(err => {});
			},
			upvideo() { //上传视频
				let _this = this;
				// 1.选择要上传的视频
				uni.chooseVideo({
					maxDuration: 60, // 拍摄视频最长拍摄时间，单位秒。最长支持 60 秒。
					sourceType: ['album', 'camera'], // album 从相册选视频，camera 使用相机拍摄，默认为：['album', 'camera']
					success: function(res) {
						_this.VIDEOuploadImageService(res.tempFilePath)
					}
				});
			},
			VIDEOuploadImageService(url) { //视频转载
				let _this = this;
				let groupinfo = this.groupInfo
				httpRequest.uploadFile('/addons/cos/index/upload1', url).then(res => {
					let data = {
						mine: {
							id: uni.getStorageSync("user_id"),
							content: res.url,
							data_type: 3, //1=文字,2=图片,3=视频
						},
						to: {
							groups_id: this.group_id,
							groupname: groupinfo.name,
							avatar: groupinfo.icon,
							sign: groupinfo.intro,
							id: groupinfo.id,
							groups: {
								id: groupinfo.id,
								name: groupinfo.name,
								user_id: groupinfo.user_id,
								icon: groupinfo.icon,
								intro: groupinfo.intro,
								status: groupinfo.status,
								createtime: groupinfo.createtime,
								updatetime: groupinfo.updatetime,
								deletetime: ""
							},
							name: groupinfo.name,
							type: "group"
						},
						client_id: uni.getStorageSync("client_id")
					}
					this.sendother(data)
				}).catch(err => {});
			},
			liwufn() {
				this.$refs.liwurefs.show = true
			},
			chuliemo(arr, num) { //转化为50等分的数组,(表情包使用)
				var newArr = []
				for (var i = 0; i < arr.length; i += num) {
					newArr.push(arr.slice(i, i + num))
				}
				return newArr
			},
			// 撤回消息
			backMsg(item) {
				if (item.user_id != this.user_id) {
					return false
				}
				let _this = this;
				uni.showActionSheet({
					itemList: ['撤回消息'],
					success: function(res) {
						if (Number(new Date() - (item.createtime * 1000) > 2 * 60 * 1000)) {
							httpRequest.toast("不能撤回超过两分钟的消息")
							return false
						}
						_this.chehui(item)
					},
					fail: function(res) {}
				});
			},
			chehui(item) {
				let data = {
					id: item.id,
					client_id: uni.getStorageSync("client_id"),
				}
				httpRequest.request('/webim/groups_message/cxMessage', 'POST', data).then(res => {
					if (res.code == 1) {
						this.list.data.forEach(current => {
							if (current.id == item.id) {
								current.msg_status = 2
							}
						})
					}
				})
			},
			updatechat() { //更新最新一一条消息到消息列表
				if (!this.isload) {
					return false
				}
				httpRequest.request('/webim/groups_message/messageHistory', 'GET', {
					page: 1,
					limit: 1,
					targetid: this.group_id,
				}).then(res => {
					if (res.data.list.length == 0) {
						return false
					}
					if (this.list.data.length != 0 && res.data.list[0].id == this.list.data[this.list.data.length -
							1].id) { //防止重复添加数据
						return false
					}
					let ids = [0]
					res.data.list.forEach(item => {
						if (item.user_id != this.user_id) {
							ids.push(item.id)
						}
					})
					this.readNews(ids.join())
					this.list.data.push(res.data.list[0])
					console.log(this.list.data, "9999");
					this.updatechatflag = false
					this.updatechatflag = true
					this.scrollToBottom()

				}).catch(err => {
					httpRequest.toast(err.msg);
				})
			},
			init(isPage, page) {
				let _this = this
				httpRequest.request('/webim/groups_message/messageHistory', 'GET', {
					page: page || 1,
					targetid: this.group_id,
				}).then(res => {
					this.isload = true
					uni.stopPullDownRefresh()
					let ids = [0]
					res.data.list.forEach(item => {
						if (item.user_id != this.user_id) {
							ids.push(item.id)
						}
					})
					this.readNews(ids.join())
					if (res.code == 0) {
						let resList = res.data;
						let dataList = _this.list;
						if (isPage == true) {
							_this.list.data = resList.list.reverse().concat(dataList.data);
							this.updatechatflag = false
							this.updatechatflag = true
						} else {
							this.list = res.data
							_this.list.data = resList.list.reverse()
							this.scrollToBottom()
						}

					}
				}).catch(err => {
					httpRequest.toast(err.msg);
				})
			},
			playBox(i) {
				this.isVideoShow = true
				let videoContext = uni.createVideoContext(`videoId${i}`)
				videoContext.play();
			},
			play(i) { // 播放时进入全屏
				let videoContext = uni.createVideoContext(`videoId${i}`, this)
				videoContext.requestFullScreen()
			},
			fullscreenchange(e, i) { //退出全屏时暂停
				if (!e.detail.fullScreen) {
					uni.createVideoContext(`videoId${i}`, this).pause();
					this.isVideoShow = false
				}
			},
			async showmodal(val) {
				uni.showLoading({
					title: "请稍后",
					mask: true
				})
				let res = await httpRequest.request('/api/user/checkYyspRule', 'GET', {
					to_user_id: this.group_id
				})
				if (res.code != 1) {
					httpRequest.toast(res.msg)
					return false
				}
				uni.hideLoading()
				this.currenti = val
				this.$refs.liwurefs.show = true
				this.$refs.liwurefs.tonghuashow = true
				this.$refs.liwurefs.tonghuajg = res.data.pl_price
			},
			readNews(ids) { //读取消息,增加已读 状态
				httpRequest.request('/api/user/setMessageStatus', 'GET', {
					ids
				}).then(res => {})
			},
			sendother(data) { //发送其他类型的消息
				httpRequest.request('/webim/groups_message/add', 'POST', data).then(res => {
					if (res.code == 0) {
						this.updatechat()
					}
				})
			},
			send(val) { //发送消息
				let content = ""
				if (val) {
					content = val
					this.cyyshow = false
				} else {
					if (this.content.trim() == "") {
						return false
					}
					content = this.content
				}

				let groupinfo = this.groupInfo
				httpRequest.request('/webim/groups_message/add', 'POST', {
					mine: {
						id: uni.getStorageSync("user_id"),
						content: content,
						data_type: 1, //1=文字,2=图片,3=视频
					},
					to: {
						groups_id: this.group_id,
						groupname: groupinfo.name,
						avatar: groupinfo.icon,
						sign: groupinfo.intro,
						id: groupinfo.id,
						groups: {
							id: groupinfo.id,
							name: groupinfo.name,
							user_id: groupinfo.user_id,
							icon: groupinfo.icon,
							intro: groupinfo.intro,
							status: groupinfo.status,
							createtime: groupinfo.createtime,
							updatetime: groupinfo.updatetime,
							deletetime: ""
						},
						name: groupinfo.name,
						type: "group"
					},
					client_id: uni.getStorageSync("client_id")
				}).then(res => {
					if (res.code == 0) {
						this.updatechat()
					}
				})
				this.content = ""

			},
			scrollToBottom() { //滚动到底部
				let that = this
				if (that.list.data.length) {
					this.$nextTick(() => {
						uni.pageScrollTo({
							selector: '#maodian' + that.list.data[that.list.data.length - 1]
								.id, // 要跳转到的锚点元素的选择器或者id
							duration: 10 // 过渡时间（单位ms）
						});
					})
				}

			},

		}
	}
</script>

<style lang="scss" scoped>
	::v-deep.uni-textarea-wrapper {
		height: 40rpx;
	}

	.lanbgc {
		background-color: #c1282e !important;
		color: #fff !important;
	}

	.huigbc {
		background-color: #282536 !important;
		color: #fff !important;
	}

	.bottomopenbtn {
		width: 50rpx;
		height: 50rpx;
	}

	::v-deep.u-tooltip__wrapper {
		white-space: normal;
		flex-shrink: 1;
	}

	::v-deep.u-tooltip__wrapper__popup__list__btn__text {
		white-space: nowrap;
	}

	.hidden {
		display: none !important;
	}

	.record {
		width: 39vw;
		height: 39vw;
		position: fixed;
		top: 35%;
		left: 30%;
		background-color: rgba(0, 0, 0, 0.8);
		border-radius: 40rpx;
	}

	.record .ing {
		width: 100%;
		height: 30vw;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	@keyframes volatility {
		0% {
			background-position: 0% 130%;
		}

		20% {
			background-position: 0% 150%;
		}

		30% {
			background-position: 0% 155%;
		}

		40% {
			background-position: 0% 160%;
		}

		50% {
			background-position: 0% 145%;
		}

		70% {
			background-position: 0% 150%;
		}

		80% {
			background-position: 0% 170%;
		}

		90% {
			background-position: 0% 160%;
		}

		100% {
			background-position: 0% 135%;
		}
	}

	.record .ing [class*='wlIcon'] {
		background-image: linear-gradient(to bottom, #ffffff, #565656 50%);
		background-size: 100% 200%;
		animation: volatility 1.5s ease-in-out -1.5s infinite alternate;
		-webkit-background-clip: text;
		-webkit-text-fill-color: transparent;
		font-size: 140rpx;
		padding-top: 40rpx;
		color: #f09b37;
	}

	.record .cancel {
		width: 100%;
		height: 30vw;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.record .cancel [class*='wlIcon'] {
		color: #fff;
		font-size: 150rpx;
	}

	.record .tis {
		width: 100%;
		height: 10vw;
		display: flex;
		justify-content: center;
		font-size: 24rpx;
		color: #fff;
	}

	.record .tis.change {
		color: #f09b37;
	}

	.managerImg {
		width: 60%;
		height: 80%;
	}

	.removeImg {
		width: 60%;
		height: 60%;
	}

	.audioImg {
		width: 40rpx;
		height: 40rpx;
	}

	.videoBox {
		border-radius: 10rpx;
		width: 400rpx;
		height: 300rpx;
		// background-color: #000;
		position: relative;
		background-size: 100% 100%;
	}

	.videoBox::after {
		content: '';
		width: 50rpx;
		height: 50rpx;
		// background-image: url('@/static/image/sysem/dz.png');
		background-size: 100% 100%;
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
	}

	.service_box {
		height: 200rpx;
	}

	.item_service_box {
		z-index: 1000000;
		width: 25%;
		margin-top: 15rpx;

	}

	.item_service {
		width: 150rpx;
		height: 150rpx;
		border: 1rpx solid rgba(255, 255, 255, .06);
	}

	.foot {
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		background-color: #fff;
		z-index: 100;
	}

	.swiper {
		background-color: #ffffff;
		height: 350rpx;
	}

	.emote {
		padding: 0 30rpx 30rpx;
	}

	.item_emote_box {
		z-index: 1000000;
		width: 10%;
		margin-top: 15rpx;

	}

	.item_emote_img {
		width: 80rpx;
		height: 80rpx;
	}

	.imgJia {
		width: 48rpx;
		height: 48rpx;
		margin-top: -5rpx;
	}

	::v-deep.u-navbar--fixed {
		z-index: 100000 !important;
	}
</style>